<?php
#+------------------------------------------------------------------
#| 普通的。
#+------------------------------------------------------------------
#| Author:Janmas Cromwell <janmas-cromwell@outlook.com>
#+------------------------------------------------------------------
namespace app\library\websocket\action;

use app\library\websocket\tool\Package;
use app\library\websocket\tool\Pusher;
use Swoole\WebSocket\Frame;
use Swoole\WebSocket\Server;
use think\helper\Str;

abstract class MessageCenter
{
	/**
	 * websocket服务
	 * @var Server
	 */
	protected $server;

	/**
	 * 消息内容
	 * @var Frame|null
	 */
	protected $frame;

	/**
	 * 客户端发来的消息
	 * @var mixed
	 */
	protected $message;

	/**
	 * 往客户端发送消息的实体
	 * @var Push
	 */
	protected $pusher;

	/**
	 * 客户端id
	 * @var int
	 */
	protected $fd;

	/**
	 * 目标的加密user_id或者群组id
	 * @var
	 */
	protected $to;

	/**
	 * 当前会话id
	 * @var string
	 */
	protected $chatId;
	/**
	 * 是否群组消息
	 * @var bool
	 */
	protected $isGroup = false;

	/**
	 * @param Server $server
	 * @param Frame|null $frame
	 */
	public function __construct(Server $server, Frame $frame = null)
	{
		$this->pusher = new Pusher($server);
		$this->server = $server;
		$this->fd = $frame->fd;
		if (!is_null($frame)) {
			$this->message = new Package($frame);
			#TODO:校验消息是否合法
			$this->to = property_exists($this->message, 'to') ? $this->message->to : null;
			$this->isGroup = property_exists($this->message, 'type') ? (bool)$this->message->type : false;
			$this->chatId = property_exists($this->message, 'chatId') ? $this->message->chatId : null;
		}
	}

	abstract public function handle();

	/**
	 * 获取当前action
	 * @return string
	 */
	protected function getAction()
	{
		$class = explode('\\', static::class);
		return Str::snake(array_pop($class));
	}

	/**
	 * 消息检验
	 * @return void
	 */
	protected function chk()
	{

	}

}
